import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'l10n/app_localizations.dart';
import 'package:provider/provider.dart' as provider;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:window_manager/window_manager.dart';
import 'models/service_item.dart';
import 'widgets/service_list_widget.dart';
import 'widgets/sidebar_widget.dart';
import 'widgets/custom_title_bar.dart';
import 'pages/settings_page.dart';
import 'pages/splash_page.dart';
import 'pages/login_page.dart';
import 'pages/config_page.dart';
import 'utils/language_manager.dart';
import 'utils/theme_manager.dart';
import 'services/legacy_compatibility.dart';
import 'services/providers/tunnel_provider_compat.dart';
import 'providers/auth_provider.dart';
import 'services/providers/auth_provider.dart' as new_auth;
import 'config/app_config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'theme/app_colors.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 window_manager（Windows、Linux 和 macOS 自定义标题栏）
  if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
    await windowManager.ensureInitialized();
    
    WindowOptions windowOptions = WindowOptions(
      size: const Size(900, 650),  // 固定窗口尺寸
      minimumSize: const Size(900, 650),  // 最小尺寸
      maximumSize: const Size(900, 650),  // 最大尺寸（固定不可调整）
      center: true,
      backgroundColor: Colors.transparent,
      skipTaskbar: false,
      // 所有桌面平台都使用隐藏标题栏（macOS 通过原生代码保留红绿灯按钮）
      titleBarStyle: TitleBarStyle.hidden,
    );
    
    windowManager.waitUntilReadyToShow(windowOptions, () async {
      await windowManager.show();
      await windowManager.focus();
      await windowManager.setResizable(false);  // 禁用窗口拉伸
    });
  }
  
  // 在调试模式下优化键盘事件错误处理（这是Flutter在macOS上的已知问题）
  if (kDebugMode) {
    // 重置键盘状态，清除可能的状态混乱
    try {
      HardwareKeyboard.instance.clearState();
    } catch (e) {
      debugPrint('键盘状态重置失败: $e');
    }
    
    // 保存原始错误处理器
    final originalOnError = FlutterError.onError;
    
    // 用于限制重复警告的计数器
    int keyboardWarningCount = 0;
    
    // 设置自定义错误处理策略
    FlutterError.onError = (FlutterErrorDetails details) {
      // 检查是否为键盘重复按键检测错误
      final isKeyboardError = details.exception.toString().contains('KeyDownEvent') && 
                             details.exception.toString().contains('already pressed') &&
                             details.library == 'services library';
      
      if (isKeyboardError) {
        // 只显示一次警告
        if (keyboardWarningCount == 0) {
          debugPrint('⚠️  macOS键盘事件已优化，应用功能正常');
          keyboardWarningCount++;
        }
        // 完全静默处理后续错误，不影响键盘功能
        return;
      }
      
      // 其他错误正常处理
      if (originalOnError != null) {
        originalOnError(details);
      } else {
        FlutterError.presentError(details);
      }
    };
  }
  
  // 配置初始化
  debugPrint('🔧 main: 开始初始化配置');
  
  // 初始化配置
  await AppConfig.instance.initialize();
  debugPrint('✅ main: 配置初始化完成');
  
  // 创建ProviderContainer用于Riverpod
  final container = ProviderContainer();
  
  runApp(
    UncontrolledProviderScope(
      container: container,
      child: provider.MultiProvider(
        providers: [
          provider.ChangeNotifierProvider(create: (context) => LanguageManager()),
          provider.ChangeNotifierProvider(create: (context) => AuthProvider()),
          provider.ChangeNotifierProvider(create: (context) => ThemeManager()),
          provider.ChangeNotifierProvider(create: (context) => TunnelProvider()),
        ],
        child: const InternalNetBridgeApp(),
      ),
    ),
  );
}

// 会员类型枚举
enum MembershipType {
  free,     // 免费版
  premium,  // 普通会员
  vip,      // 高级会员
}

// 会员信息类
class MembershipInfo {
  final MembershipType type;
  final String displayName;
  final int maxServices;
  final Color color;

  const MembershipInfo({
    required this.type,
    required this.displayName,
    required this.maxServices,
    required this.color,
  });

  static Map<MembershipType, MembershipInfo> _membershipData(BuildContext context) => {
    MembershipType.free: MembershipInfo(
      type: MembershipType.free,
      displayName: AppLocalizations.of(context)!.freeVersion,
      maxServices: 1,
      color: AppColors.of(context).onSurface.withOpacity(0.6),
    ),
    MembershipType.premium: MembershipInfo(
      type: MembershipType.premium,
      displayName: AppLocalizations.of(context)!.premiumMember,
      maxServices: 3,
      color: AppColors.of(context).primary,
    ),
    MembershipType.vip: MembershipInfo(
      type: MembershipType.vip,
      displayName: AppLocalizations.of(context)!.vipMember,
      maxServices: 10,
      color: AppColors.of(context).secondary,
    ),
  };

  static MembershipInfo getInfo(MembershipType type, BuildContext context) {
    return _membershipData(context)[type]!;
  }
}

class InternalNetBridgeApp extends ConsumerWidget {
  const InternalNetBridgeApp({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return provider.Consumer2<LanguageManager, ThemeManager>(
      builder: (context, languageManager, themeManager, child) {
        // 监听认证状态
        final authState = ref.watch(new_auth.authProvider);
        
        return MaterialApp(
          title: AppLocalizations.of(context)?.appTitle ?? 'Internal Net Bridge',
          locale: languageManager.currentLocale,
          localizationsDelegates: const [
            AppLocalizations.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          supportedLocales: const [
            Locale('zh', 'CN'),
            Locale('en', 'US'),
          ],
          theme: themeManager.themeData,
          home: _buildHome(authState),
          routes: {
            '/login': (context) => const LoginPage(),
            '/main': (context) => const MainPage(),
          },
          debugShowCheckedModeBanner: false,
        );
      },
    );
  }
  
  Widget _buildHome(new_auth.AuthState authState) {
    // 如果正在加载，显示启动页面
    if (authState.isLoading) {
      return const SplashPage();
    }
    
    // 如果已认证，直接进入主页面
    if (authState.isAuthenticated) {
      return const MainPage();
    }
    
    // 未认证，进入登录页面
    return const LoginPage();
  }
}

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  int _selectedIndex = 0;
  MembershipType _currentMembership = MembershipType.premium; // 当前会员类型
  bool _isSidebarCollapsed = false; // 侧边栏是否折叠
  
  // 服务实例
  final AppService _appService = AppService();
  
  // 服务列表状态管理
  List<ServiceItem> _services = [];
  List<ServiceItem> _localServices = []; // 本地服务列表（如有需要）
  bool _isLoading = false;
  String? _errorMessage;
  Set<String> _loadingServices = {}; // 记录正在加载的服务ID
  bool _isInitialLoad = true; // 标记是否为初始加载
  
  @override
  void initState() {
    super.initState();
    // 延迟执行以避免在组件构建期间修改Provider状态
    Future(() => _loadServices());
  }
  
  // 加载服务列表
  Future<void> _loadServices() async {
    // 直接调用刷新服务方法
    await _refreshServices();
  }
  
  // 刷新服务列表
  Future<void> _refreshServices() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });
    
    try {
      // 从后端获取隧道列表
      final tunnelProvider = provider.Provider.of<TunnelProvider>(context, listen: false);
      await tunnelProvider.fetchTunnels();
      
      setState(() {
        _isLoading = false;
      });
      
      // 只在初始加载时自动重连状态为active的服务
      if (_isInitialLoad) {
        debugPrint('');
        debugPrint('╔══════════════════════════════════════════════════════════════╗');
        debugPrint('║  🔍 检查自动重连条件                                          ║');
        debugPrint('╚══════════════════════════════════════════════════════════════╝');
        debugPrint('📊 从服务端获取到 ${tunnelProvider.tunnels.length} 个隧道');
        
        // 从tunnelProvider获取最新的隧道数据转换为ServiceItem
        final tunnelServices = tunnelProvider.tunnels.map((tunnel) {
          final isConnected = tunnel.status == 'active' || tunnel.isConnected == true;
          
          // 打印每个隧道的详细信息
          debugPrint('');
          debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
          debugPrint('隧道: ${tunnel.serverName}');
          debugPrint('  ├─ ID: ${tunnel.tunnelId}');
          debugPrint('  ├─ 地址: ${tunnel.localHost}:${tunnel.localPort}');
          debugPrint('  ├─ 协议: ${tunnel.tunnelType}');
          debugPrint('  ├─ status字段: ${tunnel.status ?? "(null)"}');
          debugPrint('  ├─ isConnected字段: ${tunnel.isConnected ?? "(null)"}');
          debugPrint('  └─ 判定为active: ${tunnel.status == 'active' ? "✅ 是" : "❌ 否"}');
          
          return ServiceItem(
            id: tunnel.tunnelId,
            name: tunnel.serverName,
            ip: tunnel.localHost,
            port: int.tryParse(tunnel.localPort) ?? 3000,
            icon: tunnel.tunnelType == 'tcp' ? Icons.settings_ethernet : Icons.http,
            isEnabled: isConnected,
            tunnelId: tunnel.tunnelId,
            protocol: tunnel.tunnelType,
            customDomain: tunnel.publicAddress,
            status: tunnel.status,
          );
        }).toList();
        
        final allServices = [...tunnelServices, ..._localServices];
        
        debugPrint('');
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint('📋 总服务数: ${allServices.length}');
        debugPrint('   ├─ 隧道服务: ${tunnelServices.length}');
        debugPrint('   └─ 本地服务: ${_localServices.length}');
        
        final activeServices = allServices.where((s) => s.status == 'active').toList();
        debugPrint('');
        debugPrint('🔍 状态为active的服务: ${activeServices.length} 个');
        for (final service in activeServices) {
          debugPrint('   • ${service.name} (${service.tunnelId})');
        }
        
        if (activeServices.isEmpty) {
          debugPrint('');
          debugPrint('⚠️  没有检测到active状态的服务，跳过自动重连');
          debugPrint('');
        } else {
          debugPrint('');
          debugPrint('🚀 开始自动重连...');
          await _autoReconnectActiveServices(allServices);
        }
        
        _isInitialLoad = false;
      }
      
      // 显示刷新成功提示
      if (mounted) {
        final tunnelProvider = provider.Provider.of<TunnelProvider>(context, listen: false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('服务列表已刷新 (${tunnelProvider.tunnels.length}个服务)'),
            duration: const Duration(seconds: 2),
            backgroundColor: AppColors.of(context).success,
          ),
        );
      }
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _isLoading = false;
      });
      
      // 显示错误提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: SelectableText('刷新失败: $e'),
            duration: const Duration(seconds: 3),
            backgroundColor: AppColors.of(context).error,
          ),
        );
      }
    }
  }

  // 获取当前启用的服务数量
  int get _enabledServicesCount {
    return _services.where((service) => service.isEnabled).length;
  }

  // 检查是否可以启用更多服务
  bool _canEnableMoreServices() {
    final membershipInfo = MembershipInfo.getInfo(_currentMembership, context);
    return _enabledServicesCount < membershipInfo.maxServices;
  }

  // 显示升级会员对话框
  void _showUpgradeDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Theme.of(context).dialogBackgroundColor,
          title: Text(
            AppLocalizations.of(context)!.upgradeRequired,
            style: TextStyle(color: Theme.of(context).textTheme.titleLarge?.color),
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                AppLocalizations.of(context)!.serviceLimitReached,
                style: TextStyle(color: Theme.of(context).textTheme.bodyMedium?.color),
              ),
              const SizedBox(height: 16),
              Text(
                AppLocalizations.of(context)!.upgradeToEnableMore,
                style: TextStyle(color: Theme.of(context).textTheme.bodyMedium?.color),
              ),
              const SizedBox(height: 12),
              _buildMembershipOption(MembershipType.premium),
              const SizedBox(height: 8),
              _buildMembershipOption(MembershipType.vip),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text(AppLocalizations.of(context)!.cancel),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
                // 这里可以跳转到升级页面
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.of(context).primary,
              ),
              child: Text(AppLocalizations.of(context)!.upgradeNow),
            ),
          ],
        );
      },
    );
  }

  Widget _buildMembershipOption(MembershipType type) {
    final info = MembershipInfo.getInfo(type, context);
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Theme.of(context).cardColor,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: info.color.withOpacity(0.3),
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.star,
            color: info.color,
            size: 20,
          ),
          const SizedBox(width: 8),
          Text(
            info.displayName,
            style: TextStyle(
              color: info.color,
              fontWeight: FontWeight.bold,
            ),
          ),
          const Spacer(),
          Text(
                AppLocalizations.of(context)!.maxServices(info.maxServices),
                style: TextStyle(
                  color: Theme.of(context).textTheme.bodySmall?.color,
                  fontSize: 12,
                ),
              ),
        ],
      ),
    );
  }
  
  // 创建新服务的隧道
  Future<void> _createTunnelForNewService(String ip, int port) async {
    try {
      final serviceId = 'manual_${ip}_$port';
      final success = true; // 简化处理
      
      if (success) {
        // 刷新服务列表
        await _refreshServices();
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('服务隧道创建成功'),
              backgroundColor: AppColors.of(context).success,
              duration: const Duration(seconds: 2),
            ),
          );
        }
      } else {
        throw Exception('隧道创建失败');
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('创建隧道失败: $e'),
            backgroundColor: AppColors.of(context).error,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    }
  }
  
  // 显示编辑服务对话框
  void _showEditServiceDialog(ServiceItem service) {
    // 编辑功能暂时禁用
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('编辑功能暂时不可用')),
    );
  }
  
  // 删除服务
  Future<void> _deleteService(ServiceItem service) async {
    if (service.tunnelId == null || service.tunnelId!.isEmpty) {
      // 本地服务或无效的tunnelId，不能删除
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('本地服务不可删除'),
            backgroundColor: Colors.orange,
            duration: Duration(seconds: 2),
          ),
        );
      }
      return;
    }
    
    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除隧道 "${service.name}" 吗？\n此操作不可撤销。'),
        actions: [
          // 使用 Row 让按钮左右各占一半
          Row(
            children: [
              Expanded(
                child: TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: const Text('取消'),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: TextButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  style: TextButton.styleFrom(
                    foregroundColor: Colors.red,
                  ),
                  child: const Text('删除'),
                ),
              ),
            ],
          ),
        ],
      ),
    );
    
    if (confirmed != true) {
      return;
    }
    
    try {
      debugPrint('🗑️  开始删除隧道: ${service.name} (${service.tunnelId})');
      
      // 调用AppService删除隧道
      final success = await _appService.deleteTunnel(service.tunnelId!);
      
      if (success) {
        debugPrint('✅ 隧道删除成功: ${service.name}');
        
        // 刷新服务列表
        await _refreshServices();
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('隧道 "${service.name}" 已删除'),
              backgroundColor: Colors.green,
              duration: const Duration(seconds: 2),
            ),
          );
        }
      } else {
        throw Exception('删除失败');
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除隧道失败: $e'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // 获取路由参数
    final arguments = ModalRoute.of(context)?.settings.arguments;
    if (arguments is int) {
      // 如果有路由参数，设置选中的页面索引
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          setState(() {
            _selectedIndex = arguments;
          });
        }
      });
    }
    
    final screenWidth = MediaQuery.of(context).size.width;
    final isSmallScreen = screenWidth < 768;
    final isMobile = screenWidth < 600; // 真正的移动端
    
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      resizeToAvoidBottomInset: false,
      body: Column(
        children: [
          // 自定义标题栏（仅 Windows 和 Linux）
          const CustomTitleBar(
            title: '内网穿透桥接',
          ),
          // 主内容区域
          Expanded(
            child: ClipRect(
              child: isMobile 
                ? _buildMainContent(isSmallScreen) // 移动端只显示主内容
                : Row(
                    children: [
                      // 左侧导航栏（桌面端和平板）
                      Container(
                        width: _isSidebarCollapsed ? 60 : (isSmallScreen ? 200 : 250),
                        constraints: const BoxConstraints(
                          minWidth: 60,
                          maxWidth: 300,
                        ),
                        child: SidebarWidget(
                          selectedIndex: _selectedIndex,
                          isCollapsed: _isSidebarCollapsed,
                          onItemSelected: (index) {
                            setState(() {
                              _selectedIndex = index;
                            });
                          },
                          onToggleCollapse: () {
                            setState(() {
                              _isSidebarCollapsed = !_isSidebarCollapsed;
                            });
                          },
                          isSmallScreen: isSmallScreen,
                          currentMembership: _currentMembership.toString().split('.').last,
                          enabledServicesCount: _enabledServicesCount,
                          onMembershipTap: () {
                            if (_currentMembership != MembershipType.vip) {
                              _showUpgradeDialog();
                            }
                          },
                        ),
                      ),
                      // 主内容区域
                      Expanded(
                        child: ClipRect(
                          child: _buildMainContent(isSmallScreen),
                        ),
                      ),
                    ],
                  ),
            ),
          ),
        ],
      ),
      // 移动端底部导航栏
      bottomNavigationBar: isMobile 
        ? BottomNavigationBar(
            currentIndex: _selectedIndex,
            onTap: (index) {
              setState(() {
                _selectedIndex = index;
              });
            },
            type: BottomNavigationBarType.fixed,
            selectedItemColor: Theme.of(context).colorScheme.primary,
            unselectedItemColor: Colors.grey,
            selectedFontSize: 12,
            unselectedFontSize: 11,
            items: const [
              BottomNavigationBarItem(
                icon: Icon(Icons.home),
                label: '首页',
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.settings),
                label: '设置',
              ),
            ],
          )
        : null,
    );
  }

  Widget _buildMainContent(bool isSmallScreen) {
    switch (_selectedIndex) {
      case 0: // 首页
        return Padding(
          padding: EdgeInsets.all(isSmallScreen ? 8 : 16),
          child: provider.Consumer<TunnelProvider>(
            builder: (context, tunnelProvider, child) {
              // 当TunnelProvider状态改变时，重新构建ServiceItem列表
              final tunnelServices = tunnelProvider.tunnels.map((tunnel) {
                // 优先使用status字段，active表示已连接，inactive表示未连接
                final isConnected = tunnel.status == 'active' || tunnel.isConnected == true;
                return ServiceItem(
                  id: tunnel.tunnelId,
                  name: tunnel.serverName,
                  ip: tunnel.localHost,
                  port: int.tryParse(tunnel.localPort) ?? 3000,
                  icon: tunnel.tunnelType == 'tcp' ? Icons.settings_ethernet : Icons.http,
                  isEnabled: isConnected,
                  tunnelId: tunnel.tunnelId,
                  protocol: tunnel.tunnelType,
                  customDomain: tunnel.publicAddress, // 使用后端返回的public_url
                  status: tunnel.status, // 传递status字段
                );
              }).toList();

              // 合并隧道服务和本地服务
              final allServices = [...tunnelServices, ..._localServices];

              return ServiceListWidget(
                services: allServices,
                canEnableMoreServices: _canEnableMoreServices,
                onUpgradeRequired: _showUpgradeDialog,
                onRefresh: _refreshServices,
                isLoading: _isLoading,
                errorMessage: _errorMessage,
                loadingServices: _loadingServices,
                onAddServer: null, // 使用AddServiceDialog代替直接的回调
                onServiceEdit: (service) {
                  _showEditServiceDialog(service);
                },
                onServiceDelete: (service) {
                  _deleteService(service);
                },
                onServiceToggle: (service, value) async {
                  if (value && !_canEnableMoreServices()) {
                    _showUpgradeDialog();
                    return;
                  }
                  
                  setState(() {
                    _loadingServices.add(service.id);
                  });
                  
                  try {
                    // 更新服务状态（简化处理）
                    setState(() {
                      service.isEnabled = value;
                    });
                    // 这里可以添加实际的隧道管理逻辑
                    if (false) { // 占位条件
                      // 显示更新失败提示
                      if (mounted) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: SelectableText(AppLocalizations.of(context)!.serviceUpdateFailed),
                            duration: const Duration(seconds: 2),
                            backgroundColor: Colors.red,
                          ),
                        );
                      }
                    }
                  } catch (e) {
                    // 显示错误提示
                    if (mounted) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: SelectableText(AppLocalizations.of(context)!.serviceUpdateError(e.toString())),
                          duration: const Duration(seconds: 3),
                          backgroundColor: Colors.red,
                        ),
                      );
                    }
                  } finally {
                    setState(() {
                      _loadingServices.remove(service.id);
                    });
                  }
                },
              );
            },
          ),
        );
      case 1: // 设置
        return const SettingsPage();
      case 2: // 我的套餐
        return Center(
          child: Text(
            AppLocalizations.of(context)!.myPlanPage,
            style: TextStyle(color: Theme.of(context).textTheme.bodyLarge?.color, fontSize: 18),
          ),
        );
      case 3: // 配置管理（通过设置页面三次点击+密码访问）
        return const ConfigPage();
      default:
        return const SizedBox.shrink();
    }
  }

  /// 自动重连状态为active的服务（优化版）
  Future<void> _autoReconnectActiveServices(List<ServiceItem> services) async {
    final activeServices = services.where((service) => 
      service.status == 'active' && service.tunnelId != null
    ).toList();
    
    if (activeServices.isEmpty) {
      debugPrint('🔄 没有需要自动重连的服务');
      return;
    }
    
    debugPrint('╔══════════════════════════════════════════════════════════════╗');
    debugPrint('║  🔄 自动重连服务 (启动时检测到 ${activeServices.length} 个active状态的服务)  ║');
    debugPrint('╚══════════════════════════════════════════════════════════════╝');
    
    int reconnectedCount = 0;
    int skippedCount = 0;
    int failedCount = 0;
    
    // 串行处理，避免同时建立太多连接
    for (final service in activeServices) {
      try {
        debugPrint('');
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint('🔄 正在处理服务: ${service.name}');
        debugPrint('   ├─ 隧道ID: ${service.tunnelId}');
        debugPrint('   ├─ 目标地址: ${service.ip}:${service.port}');
        debugPrint('   ├─ 协议类型: ${service.protocol}');
        debugPrint('   └─ isConnected: ${service.isEnabled}');
        
        // 🔥 关键修复：启动时的自动重连应该检查实际的Go连接状态
        // 而不是持久化状态，因为持久化状态可能过时
        final appService = AppService();
        final actuallyConnected = appService.isTunnelConnected(service.tunnelId!);
        
        debugPrint('   🔍 实际连接状态检查:');
        debugPrint('      ├─ Go层连接: ${actuallyConnected ? "✅ 已连接" : "❌ 未连接"}');
        debugPrint('      └─ 服务端状态: ${service.isEnabled ? "已启用" : "未启用"}');
        
        if (actuallyConnected) {
          debugPrint('   ✓ 检测到活跃Go连接，跳过重连');
          skippedCount++;
          continue;
        }
        
        debugPrint('   → 开始建立TCP连接...');
        
        // 🔥 关键修复：使用与手动连接相同的方法
        // 手动点击使用 createAndConnectTunnel，自动重连也应该使用它
        await appService.createAndConnectTunnel(
          localHost: service.ip,
          localPort: service.port.toString(),  // 使用String类型，与手动连接一致
          serverName: service.name,
        );
        
        debugPrint('   ✅ 自动重连成功！');
        reconnectedCount++;
        
        // 小延迟，避免连接峰值
        await Future.delayed(const Duration(milliseconds: 200));
        
      } catch (e, stackTrace) {
        debugPrint('   ❌ 自动重连失败: $e');
        debugPrint('   ⚠️  堆栈信息: ${stackTrace.toString().split('\n').take(3).join('\n   ')}');
        failedCount++;
        // 继续处理下一个服务，不要因为一个失败而停止
      }
    }
    
    debugPrint('');
    debugPrint('╔══════════════════════════════════════════════════════════════╗');
    debugPrint('║  📊 自动重连统计                                              ║');
    debugPrint('╠══════════════════════════════════════════════════════════════╣');
    debugPrint('║  ✅ 成功重连: $reconnectedCount 个服务                           ');
    debugPrint('║  ⏭️  跳过重连: $skippedCount 个服务 (已有连接)                   ');
    debugPrint('║  ❌ 重连失败: $failedCount 个服务                                ');
    debugPrint('║  📋 总计处理: ${activeServices.length} 个服务                    ');
    debugPrint('╚══════════════════════════════════════════════════════════════╝');
    
    // 如果有成功重连的服务，显示用户提示
    if (reconnectedCount > 0 && mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('🔄 已自动重连 $reconnectedCount 个active状态的服务'),
          duration: const Duration(seconds: 3),
          backgroundColor: AppColors.of(context).success,
          action: SnackBarAction(
            label: '查看详情',
            textColor: Colors.white,
            onPressed: () {
              // 用户可以点击查看详细日志
              debugPrint('📋 用户点击查看自动重连详情');
            },
          ),
        ),
      );
    }
    
    // 如果有失败的服务，显示警告
    if (failedCount > 0 && mounted) {
      Future.delayed(const Duration(seconds: 3), () {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('⚠️ $failedCount 个服务重连失败，请检查网络连接'),
              duration: const Duration(seconds: 4),
              backgroundColor: Colors.orange,
              action: SnackBarAction(
                label: '重试',
                textColor: Colors.white,
                onPressed: () {
                  // 手动触发刷新，重新尝试连接
                  _refreshServices();
                },
              ),
            ),
          );
        }
      });
    }
  }

}
